<?php

declare(strict_types=1);

namespace app\controller\admin;

use app\model\admin\CateModel;
use app\model\admin\Order;
use app\model\admin\OrderItem;
use app\model\admin\Pact;
use app\model\admin\Refund;
use app\model\mini\MiniUser;
use app\model\mini\OrderLog;
use  app\service\OrderService;
use think\facade\Db;
use think\facade\Validate;
use think\Request;

class RefundController extends AdminBaseController
{
    public function refundList(Request $request)
    {
        $params = $request->param();

        $order_ids = [];

        if (isset($params['order_status'])) {
            $order_ids = Order::scope('where', [
                "order_status" => $params['order_status']
            ])->column('id');
        }
        $user_ids = [];
        if (isset($params['nickname'])) {
            $user_ids = MiniUser::scope('where', [
                "nickname" => $params['nickname']
            ])->column('id');
        }
        $orderItems = [];
        if (isset($params['refund_status'])) {
            $orderItems = OrderItem::scope('where', [
                "refund_status" => $params['refund_status']
            ])->column('id');
        }

        // $list = OrderItem::with(['order', 'user', 'refund' => function ($q) {
        //     $q->where('is_del', 0)->order('id', 'desc');
        // }])
        //     ->where('refund_status', "<>", 0)
        //     ->scope('where', $params)
        //     ->order('refund.created_at', 'desc')->paginate([
        //         'list_rows' => $this->limit,
        //         'page' => $this->page,
        //         'var_page' => $this->pageVar
        //     ]);
        $list = Refund::scope('where', $params)->with(['user', 'orderItem', 'order'])
            ->where('is_del', 0)->where(function ($q) use ($params, $user_ids) {
                if (isset($params['nickname'])) {
                    $q->whereIn('user_id', $user_ids);
                }
            })->where(function ($q) use ($params, $order_ids) {
                if (isset($params['order_status'])) {
                    $q->whereIn('order_id', $order_ids);
                }
            })->where(function ($q) use ($params, $orderItems) {
                if (isset($params['refund_status'])) {
                    $q->whereIn('order_item_id', $orderItems);
                }
            })
            ->order('id', 'desc')->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        return successPage($list);
    }

    // 仅退钱（微信退款失败补退款）
    public function onlyRefund(Request $request)
    {
        $params = $request->param();
        // $type = $params['type'];
        $id = $params['id'];
        // $orderItem = OrderItem::with(['refund', 'order'])
        //     ->find($params['id']);
        $refund = Refund::with(['orderItem'])->find($id);
        if (!$refund) {
            return error('记录不存在');
        }
        // if()
        $res = OrderService::refund($refund->orderItem->id);
        // var_dump($res);
        if ($res['result']) {
            return success();
        } else {
            return error($res['msg']);
        }
    }
    // 仅退款操作
    public function onlyRefundMoney(Request $request)
    {
        $params = $request->param();
        $type = $params['type'];
        $id = $params['id'];
        $refund = Refund::with(['orderItem'])->where('is_del', '<>', 1)->find($id);
        if (!$refund) {
            return error('记录不存在');
        }
        $order_item_id = $refund->orderItem->id;
        $orderItem = OrderItem::with(['refund' => function ($q) {
            $q->where('is_del', '<>', 1)->order('id', 'desc'); //查询未删除的订单
        }, 'order'])
            ->where([
                "refund_status" => 1,
                "refund_type" => 1,
            ])->find($order_item_id);
        if (!$orderItem) {
            return error('记录不存在');
        }
        storage_log('orderItem' . json_encode($orderItem));
        $user_id = $orderItem->user_id;
        if ($type == 1) {
            // 同意退款
            $user = MiniUser::find($user_id);
            Db::transaction(function () use ($user_id, $user, $orderItem, $id) {
                // 还没拆单的
                if (!$orderItem->old_order_id) {
                    $order_sn = "MINI" . date("YmdH") . sprintf('%04d', $user_id) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
                    // 获取退款件数
                    $refund_num = $orderItem->refund_num;
                    if ($refund_num == $orderItem->order->total_num) {
                        // 跟新退款状态
                        Db::table('user_order_item')->where('id', $orderItem->id)
                            ->update([
                                // "order_id" => $order->id,
                                // "goods_num" => $refund_num,
                                // "old_order_id" => $orderItem->order->id,
                                "updated_at" => time(),
                                'refund_status' => 2,  // 修改为已退款
                                'mark' => '同意退款',
                            ]);
                        // 更新订单为交易关闭
                        Db::table('user_order')->where('id', $orderItem->order->id)->update([
                            "order_status" => 4,
                        ]);
                        // 全额退,不需要拆单
                        OrderLog::create([
                            "order_id" => $orderItem->order->id,
                            "order_item_id" => $id,
                            "message" => "商家同意仅退款,全额退,订单交易关闭"
                        ]);
                    } else {
                        $order = Order::create([
                            "order_sn" => $order_sn,
                            "operator_id" => $user->op_id,
                            "user_id" => $user_id,
                            "user_remak" => $remark ?? '',
                            "pay_status" => 1,
                            "pay_at" => strtotime($orderItem->order->pay_at),
                            "openid" => $user->openid,
                            "order_status" => 4, // 修改为交易关闭
                            "pay_refund_status" => 1, // 修改为未申请
                            "address_id" => $orderItem->order->address_id,
                            "user_phone" => $orderItem->order->user_phone,
                            "user_address" => $orderItem->order->user_address,
                            "real_name" => $orderItem->order->real_name,
                            // 总价就是退款价格*退款件数
                            "total_price" => $orderItem->goods_price * $orderItem->refund_num,
                            "total_num" =>  $orderItem->refund_num,
                            "order_price" =>  $orderItem->goods_price * $orderItem->refund_num,
                        ]);
                        $order_id = $order->id;

                        // 获取购买同规格的商品件数
                        $goods_num = $orderItem->goods_num;
                        storage_log("goods_num" . $goods_num);
                        storage_log("refund_num" . $refund_num);
                        // 只退部分商品,剩余产品
                        $newGoodsNum = $goods_num - $refund_num;
                        if ($newGoodsNum > 0) {
                            // 同规格还有没退完的商品
                            // 还有没退的
                            $orderItemData = [
                                "order_id" => $orderItem->order->id, //使用原先的订单ID
                                "order_status" => $orderItem->order_status,
                                "goods_price" => $orderItem->goods_price,
                                "goods_num" => $newGoodsNum,
                                "user_id" => $user_id,
                                "operator_id" => $user->op_id,
                                "cost" => $orderItem->cost,
                                "user_phone" => $orderItem->user_phone,
                                "user_address" => $orderItem->user_address,
                                "real_name" => $orderItem->real_name,
                                "good_info" => json_encode($orderItem->good_info,),
                                "spec_type" => $orderItem->spec_type,
                                "freight_price" => $orderItem->freight_price,
                                "pay_id" => 0, //todo
                                "mark" => "",
                                "created_at" => $orderItem->created_at,
                                "updated_at" => $orderItem->updated_at,
                                "mark" => "",
                            ];
                            if ($orderItemData['spec_type'] == 1) {
                                // 多规格
                                $orderItemData['sku'] = json_encode($orderItem->sku);
                            }
                            // OrderItem::create($orderItem);
                            Db::table('user_order_item')->insert($orderItemData);
                        }

                        // 修改原来的订单总金额
                        // 修改原先的订单件数
                        storage_log("orderItem->order->total_price" . $orderItem->order->total_price);
                        storage_log("orderItem->order->total_num" . $orderItem->order->total_num);
                        storage_log("orderItem->refund_price" . $orderItem->refund_price);
                        storage_log("refund_num" . $refund_num);
                        Db::table('user_order')->where('id', $orderItem->order->id)->update([
                            "total_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                            "total_num" => ($orderItem->order->total_num - $refund_num),
                            // "remark" => "orderItem->order->total_price" . $orderItem->order->total_price . "orderItem->order->total_num" . $orderItem->order->total_num . "orderItem->refund_price" . $orderItem->refund_price . "refund_num" . $refund_num
                            //支付价格不作修改，因为退款需要
                            // "order_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                            "updated_at" => time()
                        ]);
                        // 更新父级id
                        Db::table('user_order_item')->where('id', $orderItem->id)
                            ->update([
                                "order_id" => $order->id,
                                "goods_num" => $refund_num,
                                "old_order_id" => $orderItem->order->id,
                                "updated_at" => time(),
                                'refund_status' => 2,  // 修改为已退款
                                'mark' => '同意退款',
                            ]);
                        // if ($refund_num < $goods_num) {
                        //     // 只退部分商品,剩余产品
                        //     $newGoodsNum = $goods_num - $refund_num;
                        //     $orderItemData = [
                        //         "order_id" => $orderItem->order->id, //使用原先的订单ID
                        //         "order_status" => $orderItem->order_status,
                        //         "goods_price" => $orderItem->goods_price,
                        //         "goods_num" => $newGoodsNum,
                        //         "user_id" => $user_id,
                        //         "cost" => $orderItem->cost,
                        //         "user_phone" => $orderItem->user_phone,
                        //         "user_address" => $orderItem->user_address,
                        //         "real_name" => $orderItem->real_name,
                        //         "good_info" => json_encode($orderItem->good_info,),
                        //         "spec_type" => $orderItem->spec_type,
                        //         "freight_price" => $orderItem->freight_price,
                        //         "pay_id" => 0, //todo
                        //         "mark" => "",
                        //         "created_at" => $orderItem->created_at,
                        //         "updated_at" => $orderItem->updated_at,
                        //         "mark" => "",
                        //     ];
                        //     if ($orderItemData['spec_type'] == 1) {
                        //         // 多规格
                        //         $orderItemData['sku'] = json_encode($orderItem->sku);
                        //     }
                        //     // OrderItem::create($orderItem);
                        //     Db::table('user_order_item')->insert($orderItemData);
                        //     // 修改原来的订单总金额
                        //     // 修改原先的订单件数
                        //     storage_log("orderItem->order->total_price" . $orderItem->order->total_price);
                        //     storage_log("orderItem->order->total_num" . $orderItem->order->total_num);
                        //     storage_log("orderItem->refund_price" . $orderItem->refund_price);
                        //     storage_log("refund_num" . $refund_num);
                        //     Db::table('user_order')->where('id', $orderItem->order->id)->update([
                        //         "total_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                        //         "total_num" => ($orderItem->order->total_num - $refund_num),
                        //         "remark" => "orderItem->order->total_price" . $orderItem->order->total_price . "orderItem->order->total_num" . $orderItem->order->total_num . "orderItem->refund_price" . $orderItem->refund_price . "refund_num" . $refund_num
                        //         //支付价格不作修改，因为退款需要
                        //         // "order_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                        //         // "updated_at" => time()
                        //     ]);

                        //     Db::table('user_order_item')->where('id', $id)->update([
                        //         "order_id" => $order->id,
                        //         "goods_num" => $refund_num,
                        //         "old_order_id" => $orderItem->order->id,
                        //         "updated_at" => time()
                        //     ]);
                        // } else {
                        //     Db::table('user_order_item')->where('id', $id)->update([
                        //         "order_id" => $order->id,
                        //         // "goods_num" => $order->id,
                        //         // "order_sn" => $order_sn,
                        //         "old_order_id" => $orderItem->order->id,
                        //         "updated_at" => time()
                        //     ]);
                        // }
                        OrderLog::create([
                            "order_id" => $order->id,
                            "order_item_id" => $id,
                            "message" => "商家同意仅退款,进行拆分订单"
                        ]);
                    }
                } else {
                    // Db::table('user_order_item')->where('id', $id)->update([
                    //     "order_id" => $order->id,
                    //     // "order_sn" => $order_sn,
                    //     "old_order_id" => $orderItem->order->id,
                    //     "updated_at" => time()
                    // ]);
                }
            });
            // 微信退款
            OrderService::refund($order_item_id);
        }
        if ($type == 2) {
            // 拒绝仅退款
            Db::transaction(function () use ($params, $orderItem) {
                Db::table('user_order_item')->where('id', $orderItem->id)
                    ->update([
                        "refund_status" => 3, //修改为拒绝退款
                        "refund_reason" => $params['refund_reason'] ?? "商家拒绝仅退款,请联系客服处理！谢谢配合！", //修改为拒绝退款
                        "updated_at" => time()
                    ]);
                OrderLog::create([
                    "order_id" => $orderItem->order->id,
                    "order_item_id" => $orderItem->id,
                    "message" => "商家拒绝仅退款"
                ]);
            });
        }
        return success();
    }
    // 同意/拒绝退款
    public function refundOrder(Request $request)
    {
        $params = $request->param();
        $type = $params['type'];
        $refund = Refund::with(['orderItem'])->where('is_del', '<>', 1)->find($params['id']);
        if (!$refund) {
            return error('记录不存在');
        }
        $order_item_id = $refund->orderItem->id;
        // 同意退货退款
        $info = OrderItem::with(['refund' => function ($q) {
            $q->where('is_del', '<>', 1)->order('id', 'desc'); //查询未删除的订单
        }, 'order'])
            ->where([
                "refund_status" => 1,
                "refund_type" => 2 //退货退款的订单才需要修改为待退货
            ])->find($order_item_id);
        if (!$info) {
            return error('记录不存在');
        }
        if ($type == 1) {
            // 同意退款
            Db::transaction(function () use ($params, $info) {
                Db::table('user_order_item')->where('id', $info->id)
                    ->update([
                        "refund_status" => 5, //修改为商品待退货
                        "updated_at" => time()
                    ]);
                OrderLog::create([
                    "order_id" => $info->order->id,
                    "order_item_id" => $info->id,
                    "message" => "商家同意退货退款"
                ]);
            });
        }
        if ($type == 2) {
            // 拒绝退货退款
            Db::transaction(function () use ($params, $info) {
                Db::table('user_order_item')->where('id', $info->id)
                    ->update([
                        "refund_status" => 3, //修改为拒绝退款
                        "refund_reason" => $params['refund_reason'] ?? "商家拒绝退款,请联系客服处理！谢谢配合！", //修改为拒绝退款
                        "updated_at" => time()
                    ]);
                OrderLog::create([
                    "order_id" => $info->order->id,
                    "order_item_id" => $info->id,
                    "message" => "商家拒绝退货退款"
                ]);
            });
        }
        return success();


        // $list = OrderItem::with(['order', 'user', 'refund' => function ($q) {
        //     $q->where('is_del', 0);
        // }])
        //     ->where('refund_status', "<>", 0)
        //     ->scope('where', $params)
        //     ->order('id', 'desc')->paginate([
        //         'list_rows' => $this->limit,
        //         'page' => $this->page,
        //         'var_page' => $this->pageVar
        //     ]);
        // return successPage($list);
    }
    // 发货
    // public function sendGoods(Request $request)
    // {
    //     $params = $request->param();
    //     $info = Order::with(['orderItem'])->where('pay_status', 1)->find($params['id']);
    //     if ($info->order_status == 0) {
    //         $info->order_status = 1; //待收货
    //         $info->delivery_id = $params['delivery_id'];
    //         $info->send_time = time();
    //         $info->save();
    //         // todo模版通知用户
    //         return success();
    //     } else {
    //         return error('当前订单不允许发货');
    //     }
    // }
    // 确认收货
    public function confirmReceive(Request $request)
    {
        $params = $request->param();
        $info = Order::with(['orderItem'])->where('pay_status', 1)->find($params['id']);
        if ($info->order_status == 1) {
            $info->order_status = 2; //已收货，交易完成
            // $info->delivery_id = $params['delivery_id'];
            $info->save();
            // todo模版通知用户
            OrderService::handleCommission($params['id']);
            // 结算收益
            return success();
        } else {
            return error('当前订单不允许确认收货');
        }
    }
    // todo同步仅退款方法
    // 确认收货 退款
    public function confirmRefund(Request $request)
    {
        // 将订单拆分
        $id = input('id');
        // is_del退款处理完成该字段就会修改为删除 1
        $refund = Refund::with(['orderItem'])->where('is_del', '<>', 1)->find($id);
        if (!$refund) {
            return error('记录不存在');
        }
        $order_item_id = $refund->orderItem->id;
        $orderItem = OrderItem::with(['order', 'refund' => function ($q) {
            $q->where('is_del', '<>', 1)->order('id', 'desc');
        }])->where([
            'id' => $order_item_id
        ])->find();
        if (!$orderItem) {
            return error('记录不存在');
        }
        $user_id = $orderItem->user_id;
        // var_dump($orderItem->toArray());
        $user = MiniUser::find($user_id);
        // 创建一个新的order
        Db::transaction(function () use ($user_id, $user, $orderItem) {
            // 还没拆单的
            if (!$orderItem->old_order_id) {
                $order_sn = "MINI" . date("YmdH") . sprintf('%04d', $user_id) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
                // 获取退款件数
                $refund_num = $orderItem->refund_num;
                if ($refund_num == $orderItem->order->total_num) {
                    // 全额退,不需要拆单
                    Db::table('user_order_item')->where('id', $orderItem->id)
                        ->update([
                            // "order_id" => $order->id,
                            // "goods_num" => $refund_num,
                            // "old_order_id" => $orderItem->order->id,
                            "updated_at" => time(),
                            'refund_status' => 2,  // 修改为已退款，小程序端会显示该状态
                            'mark' => '同意退款',
                        ]);
                    // 更新订单为交易关闭
                    Db::table('user_order')->where('id', $orderItem->order->id)->update([
                        "order_status" => 4,
                    ]);
                    OrderLog::create([
                        "order_id" => $orderItem->order->id,
                        "order_item_id" => $orderItem->id,
                        "message" => "商品已发货，商家同意仅退款,全额退,订单交易关闭"
                    ]);
                } else {
                    $order = Order::create([
                        "order_sn" => $order_sn,
                        "user_id" => $user_id,
                        "operator_id" => $user->op_id,
                        "user_remak" => $remark ?? '',
                        "pay_status" => 1,
                        "openid" => $user->openid,
                        "order_status" => 4, //修改为交易关闭
                        "pay_refund_status" => 1, // 修改为未申请 退款订单在支付退款成功中会修改为退款成功
                        "address_id" => $orderItem->order->address_id,
                        "user_phone" => $orderItem->order->user_phone,
                        "user_address" => $orderItem->order->user_address,
                        "real_name" => $orderItem->order->real_name,
                        // 总价就是退款价格*退款件数
                        "total_price" => $orderItem->goods_price * $orderItem->refund_num,
                        "total_num" =>  $orderItem->refund_num,
                        "order_price" =>  $orderItem->goods_price * $orderItem->refund_num,
                    ]);
                    // 获取购买同规格的商品件数
                    $goods_num = $orderItem->goods_num;
                    $newGoodsNum = $goods_num - $refund_num;
                    if ($newGoodsNum > 0) {
                        // 同规格还有没退完的商品
                        $orderItemData = [
                            "order_id" => $orderItem->order->id, //使用原先的订单ID
                            "order_status" => $orderItem->order_status,
                            "goods_price" => $orderItem->goods_price,
                            "goods_num" => $newGoodsNum,
                            "user_id" => $user_id,
                            "cate_id" => $orderItem->cate_id,
                            "goods_id" => $orderItem->goods_id,
                            "cost" => $orderItem->cost,
                            "user_phone" => $orderItem->user_phone,
                            "user_address" => $orderItem->user_address,
                            "real_name" => $orderItem->real_name,
                            "good_info" => json_encode($orderItem->good_info,),
                            "spec_type" => $orderItem->spec_type,
                            "freight_price" => $orderItem->freight_price,
                            "pay_id" => 0, //todo
                            "mark" => "",
                            "created_at" => $orderItem->created_at,
                            "updated_at" => $orderItem->updated_at,
                            "mark" => "",
                        ];
                        if ($orderItemData['spec_type'] == 1) {
                            // 多规格
                            $orderItemData['sku'] = json_encode($orderItem->sku);
                        }
                        Db::table('user_order_item')->insert($orderItemData);
                    }
                    // if ($refund_num < $goods_num) {
                    //     // 只退部分商品,剩余产品
                    //     $newGoodsNum = $goods_num - $refund_num;
                    //     $orderItemData = [
                    //         "order_id" => $orderItem->order->id, //使用原先的订单ID
                    //         "order_status" => $orderItem->order_status,
                    //         "goods_price" => $orderItem->goods_price,
                    //         "goods_num" => $newGoodsNum,
                    //         "user_id" => $user_id,
                    //         "cost" => $orderItem->cost,
                    //         "user_phone" => $orderItem->user_phone,
                    //         "user_address" => $orderItem->user_address,
                    //         "real_name" => $orderItem->real_name,
                    //         "good_info" => json_encode($orderItem->good_info,),
                    //         "spec_type" => $orderItem->spec_type,
                    //         "freight_price" => $orderItem->freight_price,
                    //         "pay_id" => 0, //todo
                    //         "mark" => "",
                    //         "created_at" => $orderItem->created_at,
                    //         "updated_at" => $orderItem->updated_at,
                    //         "mark" => "",
                    //     ];
                    //     if ($orderItemData['spec_type'] == 1) {
                    //         // 多规格
                    //         $orderItemData['sku'] = json_encode($orderItem->sku);
                    //     }
                    //     Db::table('user_order_item')->insert($orderItemData);
                    Db::table('user_order')->where('id', $orderItem->order->id)->update([
                        "total_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                        "total_num" => ($orderItem->order->total_num - $refund_num),
                        //支付价格不作修改，因为退款需要
                        // "order_price" => ($orderItem->order->total_price - $orderItem->refund_price),
                        "updated_at" => time()
                    ]);
                    // 更新父级id
                    Db::table('user_order_item')->where('id', $orderItem->id)->update([
                        "order_id" => $order->id,
                        "goods_num" => $refund_num,
                        "old_order_id" => $orderItem->order->id,
                        "updated_at" => time(),
                        'refund_status' => 2,  // 修改为同意退款
                        'mark' => '同意退款',
                    ]);
                    // } else {
                    //     Db::table('user_order_item')->where('id', $id)->update([
                    //         "order_id" => $order->id,
                    //         // "goods_num" => $order->id,
                    //         // "order_sn" => $order_sn,
                    //         "old_order_id" => $orderItem->order->id,
                    //         "updated_at" => time()
                    //     ]);
                    // }
                    OrderLog::create([
                        "order_id" => $order->id,
                        "order_item_id" => $orderItem->id,
                        "message" => "商家同意仅退款,进行拆分订单"
                    ]);
                }
            } else {
                // !!$orderItem->old_order_id
            }

            // 
            // OrderLog::create([
            //     "order_id" => $order->id,
            //     "order_item_id" => $id,
            //     "message" => "商家收到货同意退款,进行拆分订单"
            // ]);
            // Db::table('user_order_item')->where('id', $id)->update([
            //     "order_id" => $order->id,
            //     // "order_sn" => $order_sn,
            //     "old_order_id" => $orderItem->order->id,
            //     "updated_at" => time()
            // ]);
        });
        // var_dump(OrderItem::find($id)->toArray());
        // 微信退款
        OrderService::refund($order_item_id);
        return success();
    }
}
